package tjx.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

//@WebFilter(filterName = "LoginFilter")
public class Filter0_LoginFilter implements Filter {
    public Filter0_LoginFilter(){}{
        System.out.println("LogFilter的LogFilter()方法运行"+new Date());
    }
    public void init(FilterConfig filterConfig)throws ServletException{
        System.out.println("LogFilter的init()方法运行"+new Date());
    }
    public void destroy() {
        System.out.println("LogFilter的destory()方法运行"+new Date());
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        //System.out.println("LogFilter的Filter方法()"+new Date());
        //java.lang.String encoding=config.getInitParameter("encoding");
        //servletRequest.setCharacterEncoding(encoding);
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpSession session=req.getSession(true);
        String username=(String)session.getAttribute("username");
        String path=req.getServletPath();
        if ("/login".equals(path))
        {
            filterChain.doFilter(servletRequest,servletResponse);
            System.out.println("用户请求登录,时间："+new Date());
        }
        else
        {
            if(username==null)
            {
                System.out.println("用户未登录,时间："+new Date());
                req.getRequestDispatcher("login.jsp").forward(req,servletResponse);
            }else
            {
                filterChain.doFilter(servletRequest,servletResponse);
                System.out.println("用户已经登录,时间："+new Date());
            }
        }
        //System.out.println("LogFilter的doFilter()方法运行--req"+new Date());
        // chain.doFilter(request, response);
        //System.out.println("LogFilter的doFilter()方法运行--resp"+new Date());
    }


}
